import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';

const Counter2: React.FC = () => {
  const [count, setCount] = useState(0);
  const [isAutoCount, setIsAutoCount] = useState(false);

  // 自动计数效果
  useEffect(() => {
    let intervalId: number | undefined;
    if (isAutoCount) {
      intervalId = setInterval(() => {
        setCount((prevCount) => prevCount + 1);
      }, 1000);
    }
    // 清理函數
    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [isAutoCount]);

  // 更新页面标题
  useEffect(() => {
    document.title = `当前计数: ${count}`;
  }, [count]);

  return (
    <div className="p-4 bg-gray-100 rounded-lg shadow-md">
      <h2 className="mb-4 text-2xl font-bold">计数器</h2>
      <p className="mb-4 text-xl">当前计数: {count}</p>
      <div className="mb-4 space-x-2">
        <Button onClick={() => setCount(count + 1)}>增加</Button>
        <Button variant="outline" onClick={() => setCount(count - 1)}>
          减少
        </Button>
      </div>
      <Button
        variant={isAutoCount ? 'destructive' : 'secondary'}
        onClick={() => setIsAutoCount(!isAutoCount)}
      >
        {isAutoCount ? '停止自动计数' : '开始自动计数'}
      </Button>
    </div>
  );
};

export default Counter2;
